namespace EyeOpen.Data
{
	using System;
	using System.Collections;
	using System.Collections.Generic;
	using System.Linq;
	using System.Linq.Expressions;

	using EyeOpen.Domain;

	public class Repository<T> 
		: IRepository<T> where T : class, IEntity
	{
		private readonly IQueryable<T> queryable;
		private readonly Action<T> add;
		private readonly Action<T> delete;
		private readonly Action<T> update;

		public Repository(IQueryable<T> set, Action<T> add, Action<T> delete, Action<T> update)
		{
			this.add = add;
			this.delete = delete;
			this.update = update;
			queryable = set;
		}

		public Expression Expression
		{
			get { return queryable.Expression; }
		}

		public Type ElementType
		{
			get { return queryable.ElementType; }
		}

		public int Count
		{
			get
			{
				return queryable.Count();
			}
		}

		public bool IsReadOnly
		{
			get
			{
				return false;
			}
		}

		public IQueryProvider Provider
		{
			get { return queryable.Provider; }
		}

		public IEnumerator<T> GetEnumerator()
		{
			return queryable.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public void Add(T item)
		{
			add(item);
		}

		public bool Remove(T item)
		{
			delete(item);

			return true;
		}

		public void Update(T item)
		{
			update(item);
		}

		public T Find(IComparable key)
		{
			return
				queryable.SingleOrDefault(x => x.Id == key);
		}

		public void Clear()
		{
			throw new NotSupportedException();
		}

		public bool Contains(T item)
		{
			throw new NotSupportedException();
		}

		public void CopyTo(T[] array, int arrayIndex)
		{
			throw new NotSupportedException();
		}
	}
}